/// [Pandigital multiples](https://projecteuler.net/problem=38)
fn main() {
    let mut list = (0..=9999)
        .map(|n| (n, concatenated_product(n)))
        .filter(|(_, (s, l))| *l > 1 && is_cpandigital(s.clone()))
        .map(|(n, (s, _))| (n, s.parse::<usize>()))
        .filter(|(_, s)| s.is_ok())
        .map(|(n, s)| (n, s.unwrap()))
        .collect::<Vec<_>>();
    list.sort_by_key(|(_, s)| *s);
    for (n, s) in list.iter() {
        println!("{:4}: {}", n, s);
    }
}

fn is_cpandigital(sequence: String) -> bool {
    let mut list = sequence.chars().collect::<Vec<_>>();
    if list.len() > 9 {
        return false;
    }
    list.sort();
    if list == vec!['1', '2', '3', '4', '5', '6', '7', '8', '9'] {
        true
    } else {
        false
    }
}

fn concatenated_product(n: usize) -> (String, usize) {
    let mut sum = n.to_string();
    for i in 2..=9 {
        if sum.len() >= 9 {
            return (sum, i - 1);
        }
        sum += &(n * i).to_string();
    }
    (sum, 9)
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn is_work() {
        assert_eq!(concatenated_product(9), ("918273645".to_owned(), 5));
        assert_eq!(concatenated_product(192), ("192384576".to_owned(), 3));
        assert!(is_cpandigital(concatenated_product(192).0));
        assert!(!is_cpandigital(concatenated_product(122).0));
    }
}
